package com.bktech.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.bktech.elements.Feed;
import com.bktech.service.ServiceHandler;
import com.bktech.stupidnews.FeedActivity;
import com.bktech.stupidnews.R;

public class ViewFragment extends Fragment {

	private final String TAG = ViewFragment.class.getName();

	public String id;
	public String title;
	public String urlImage;

	private SwipeRefreshLayout swipeRefresh;
	public SwipeRefreshLayout.OnRefreshListener swipeRefreshListener;
	private ListView listview;
	private ProgressBar progressBar;
	private ViewFragmentAdapter adapter;
	private ServiceHandler serviceHandler;
	private boolean refreshing = false;
	private OnItemClickListener onItemClickListener;

	public ViewFragment(Context context, String rssId, String title,
			String urlImage) {
		this.id = rssId;
		this.title = title;
		this.urlImage = urlImage;
		adapter = new ViewFragmentAdapter(context);
		serviceHandler = new ServiceHandler();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		new DownloadTask(makeLink(id), DownloadTask.DOWNLOAD).execute();
		// onScrollListener = new AbsListView.OnScrollListener() {
		// @Override
		// public void onScrollStateChanged(AbsListView view, int scrollState) {
		// // TODO Auto-generated method stub
		// }
		//
		// @Override
		// public void onScroll(AbsListView view, int firstVisibleItem,
		// int visibleItemCount, int totalItemCount) {
		// if (firstVisibleItem == 0)
		// swipeRefresh.setEnabled(true);
		// else
		// swipeRefresh.setEnabled(false);
		// }
		// };
		swipeRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh() {
				if (!refreshing) {
					new DownloadTask(makeLink(id), DownloadTask.UPDATE)
							.execute();
				}
			}
		};

		onItemClickListener = new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(getActivity(), FeedActivity.class);
				intent.putExtra(FeedActivity.LINK_PASS,
						adapter.listFeed.get(position).originId);
				startActivity(intent);

			}
		};
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		FrameLayout layout = (FrameLayout) inflater.inflate(
				R.layout.view_fragment, container, false);
		listview = (ListView) layout.findViewById(R.id.list_view);
		swipeRefresh = (SwipeRefreshLayout) layout
				.findViewById(R.id.swipe_refresher);
		swipeRefresh.setOnRefreshListener(swipeRefreshListener);
		swipeRefresh.setColorScheme(R.color.gplus_color_1,
				R.color.gplus_color_2, R.color.gplus_color_3,
				R.color.gplus_color_4);
		progressBar = (ProgressBar) layout.findViewById(R.id.loading_spinner);
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(onItemClickListener);
		return layout;
	}

	class DownloadTask extends AsyncTask<Void, Void, Boolean> {
		private String link;
		private String Result;
		ArrayList<Feed> listResult = new ArrayList<Feed>();

		public static final int DOWNLOAD = 0;
		public static final int UPDATE = 1;
		public static final int REFRESH = 2;
		private int type;

		public DownloadTask(String link, int type) {
			this.link = link;
			if (type < 0 || type > 3) {
				Log.d(TAG, "invalid type");
			}
			this.type = type;
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			Result = serviceHandler.makeServiceCall(link, ServiceHandler.GET);
			if (Result == "" || Result == null) {
				return false;
			}
			JSONObject headObject;
			try {
				headObject = new JSONObject(Result);
				JSONArray items = headObject.getJSONArray("items");
				for (int i = 0; i < items.length(); i++) {
					JSONObject item = (JSONObject) items.get(i);
					// Not null
					Long id = item.getLong("published");
					String title = item.getString("title");
					String originId = item.getString("originId");
					// get Data May be not appear
					String summary = getData(getObject(item, "summary"),
							"content");
					String urlImage = getData(getObject(item, "visual"), "url");
					String author = getData(item, "author");
					if (type == DOWNLOAD) {
						listResult.add(new Feed(id, title, urlImage, author,
								summary, originId));
					} else if (type == REFRESH) {
						listResult.add(new Feed(id, title, urlImage, author,
								summary, originId));
					} else if (type == UPDATE) {
						if (id != adapter.getIdNewestFeed()) {
							listResult.add(new Feed(id, title, urlImage,
									author, summary, originId));
						} else {
							return true;
						}
					}

				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result) {
				if (progressBar != null) {
					progressBar.setVisibility(View.INVISIBLE);
				}
				if (type == DOWNLOAD) {
					adapter.addFeed(listResult);
				} else if (type == REFRESH) {
					adapter.addFeed(listResult);
				} else if (type == UPDATE) {
					refreshing = false;
					adapter.updateList(listResult);
					swipeRefresh.setRefreshing(false);
				}
			} else {
				if (type == DOWNLOAD) {

				} else if (type == REFRESH) {

				} else if (type == UPDATE) {
					refreshing = false;
					adapter.updateList(listResult);
					swipeRefresh.setRefreshing(false);
				}
			}

		}
	}

	private String getData(JSONObject object, String name) {

		String result = null;
		if (object == null) {
			return result;
		}
		try {
			result = object.getString(name);
		} catch (JSONException e) {
			Log.d("GET JSON DATA", "ERROR WHEN GET STRING " + name);
		}
		return result;
	}

	private JSONObject getObject(JSONObject object, String name) {
		JSONObject result = null;
		try {
			result = object.getJSONObject(name);
		} catch (JSONException e) {
			Log.d("GET JSON DATA", "ERROR WHEN GET OBJECT " + name);
		}
		return result;
	}

	public void refresh() {
		if (!refreshing) {
			progressBar.setVisibility(View.VISIBLE);
			adapter.removeAllFeed();
			new DownloadTask(makeLink(id), DownloadTask.REFRESH).execute();
		}
	}

	public String makeLink(String feedId) {
		return "http://feedly.com/v3/streams/contents?streamId=" + feedId
				+ "&count=15";
	}
}
